<script setup>
import { computed, inject, onMounted, ref } from 'vue'
import { DlMessageBox } from '../util/messagebox.js';
import { IconTopCircle, IconSearchAlt, IconCartAdd } from '../icon/index.js'
import DlLoading from '../components/DlLoading.vue'
import ProductBox from '../components/ProductBox.vue'
import SearchBox from '../components/SearchBox.vue'
import BannerBox from '../components/BannerBox.vue'

import { getHomeBannersFun } from '../api/other.js'
import { getTypesByParentFun } from '../api/type.js'
import { getHomeMiaoShaFun } from '../api/miaosha.js'
import { findRecommendProductFun } from '../api/product.js'
import { addToCartFun } from '../api/cart.js'

//banner
const bannerArr = ref([]);
function doLoadDataBanner() {
    //加载横幅数据
    if (window && window.enableDl) {
        //模拟
        setTimeout(() => {
            let dataArr = [];
            dataArr.push({ id: 1, image: './banner2.jpg' });
            for(let i=2; i<5; i++) {
                dataArr.push({ id: i, image: './banner1.jpg' });
            }
            
            //成功后执行以下操作
            bannerArr.value = [];
            dataArr.forEach( b => bannerArr.value.push(b.image) );
        }, 1000);
    } else {
        //请求api
        getHomeBannersFun().then((result)=>{
            console.log('getHomeBannersFun result:', result);
            if (result.code == 200) {
                DlMessageBox.success(result.msg);
                //成功后执行以下操作
                bannerArr.value = [];
                result.data.forEach( b => bannerArr.value.push(b.image) );
            } else {
                DlMessageBox.error(result.msg);
            }
        });
    }

}

const typeArr = ref([]);//一级分类
const typeLoading = ref(false);//加载中
const typeListWidth = ref(8.8);
const typeBaseWidth = 2.14;//单个宽度rem
//加载一级分类
function doLoadDataType() {
    typeLoading.value = true;
    if (window && window.enableDl) {
        //模拟
        setTimeout(()=>{
            let dataArr = [];
            dataArr.push({id: 1, name: '服装', image: './type/type1.jpg'});
            dataArr.push({id: 2, name: '办公设备', image: './type/type2.jpg'});
            dataArr.push({id: 3, name: '智能数码', image: './type/type3.jpg'});
            dataArr.push({id: 4, name: '厨房用品', image: './type/type4.jpg'});
            dataArr.push({id: 5, name: '水果', image: './type/type5.jpg'});
            dataArr.push({id: 6, name: '图书', image: './type/type6.jpg'});
            dataArr.push({id: 7, name: '护理清洁', image: './type/type7.jpg'});
            dataArr.push({id: 8, name: '水产生鲜', image: './type/type8.jpg'});
    
            //样式: 计算宽度
            let len = dataArr.length;
            if(len%2==1){
                len+=1;
            }
            let maxWidth = len/2 * typeBaseWidth;
            if(maxWidth > typeListWidth.value) {
                typeListWidth.value = maxWidth;
            }
    
            typeArr.value = dataArr;
            typeLoading.value = false;
        }, 1000);
    } else {
        //请求api
        getTypesByParentFun().then((result)=>{
            console.log('getTypesByParentFun result:', result);
            if (result.code == 200) {
                DlMessageBox.success(result.msg);
                let dataArr = result.data;
                //样式: 计算宽度
                let len = dataArr.length;
                if(len%2==1){
                    len+=1;
                }
                let maxWidth = len/2 * typeBaseWidth;
                if(maxWidth > typeListWidth.value) {
                    typeListWidth.value = maxWidth;
                }
                typeArr.value = dataArr;
            } else {
                DlMessageBox.error(result.msg);
            }
            typeLoading.value = false;
        });
    }

}
//去分类列表页面
function goToTypeListView(type) {
    //类别搜索页需要 大类别id
    localStorage.setItem('selectBigTypeId', type.id);
    menuCore.push('/type');
}

//底部主菜单
const homeMenuBar = inject('homeMenuBar');
const viewRef = ref(null);
const viewHeight = computed(()=>{//计算展示区域高度
    let vh = 770;
    if(viewRef.value) {
        let p = viewRef.value.parentElement;
        vh = p.offsetHeight;
    }
    if(homeMenuBar.value) {
        let h = homeMenuBar.value.offsetHeight;
        vh -= h;
    }
    return vh;
});

//滚动事件
function doChangeScroll(e) {
    // console.log('doChangeScroll:', e);
    let t = e.target;
    //回到顶部按钮处理, 显示与隐藏
    showTopBtn.value = t.scrollTop > showHideTop;

    let offsetNum = 10;//误差值
    let height = t.scrollHeight - t.offsetHeight - t.scrollTop - offsetNum;
    // 到底加载更多
    if(height <= 0) {
        console.log('滚动到底部了...');
        //如果还有数据,则加载;如果正在加载中,则不再执行
        if(!recommendProductLoading.value && currentPageNum.value < pages.value) {
            currentPageNum.value++;
            doLoadDataRecommendProduct();
        }
    }
}
const showTopBtn = ref(false);
const showHideTop = 300;//隐藏和显示的scrollTop
const topBtnStyle = computed(()=>{
    let bottom = 1;
    let right = -1.8;
    if(homeMenuBar.value) {
        let h = homeMenuBar.value.offsetHeight;
        bottom+=h;
    }
    if(showTopBtn.value) {
        right = 0.6;
    }
    return {bottom: bottom+'px', right: right+'rem'};
});
//回到顶部
function doGoTop() {
    if(viewRef.value) {
        viewRef.value.scrollTo({top: 0, behavior: 'smooth'});
    }
}

//限时秒杀
const activityOneDataArr = ref([]);//商品数据
const activityOneEndTime = ref(Date.now());//活动结束时间 毫秒值
const activityOneShowTime = ref('');//倒计时显示
const activityOneDataLoading = ref(false);
function doLoadActivityOneData() {
    activityOneDataLoading.value = true;
    //加载限时秒杀数据
    let count = 4;//展示的商品数量

    if (window && window.enableDl) {
        //模拟
        setTimeout(()=>{
            let dataArr = [];
            let miaoShaId = 1;
            //测试 活动结束时间
            let endTime = Date.now()+360000;
    
            dataArr.push({id: 1, title: '休闲男士衬衫百搭', image: './product/product1.jpg', price: 39.89, type:['L','XL','XXL'], status:1, endTime: endTime});
            dataArr.push({id: 2, title: '宁夏精品枸杞', image: './product/product5.jpg', price: 34.69, type:['1罐','2罐','3罐'], status:1, endTime: endTime});
            dataArr.push({id: 3, title: '抽纸结实耐用', image: './product/product6.jpg', price: 8.99, type:['M','L','XL'], status:1, endTime: endTime});
            dataArr.push({id: 4, title: '农村散养土鸡蛋', image: './product/product7.jpg', price: 21.90, type:['1斤','2斤','5斤'], status:1, endTime: endTime});
    
            activityOneEndTime.value = endTime;//活动结束时间 毫秒值
            clearInterval(activityOneTimer.value);//清空旧定时器
            countDownTime();//初始显示
            activityOneTimer.value = setInterval(countDownTime, 1000);//启动倒计时
            //设置 miaoShaId 
            dataArr.forEach( p => { p.miaoShaId = miaoShaId; p.endTime = endTime; } );
            activityOneDataArr.value = dataArr;
            activityOneDataLoading.value = false;
        },1000);
    } else {
        //请求api
        getHomeMiaoShaFun(count).then((result)=>{
            console.log('getHomeMiaoShaFun result:', result);
            if (result.code == 200) {
                //DlMessageBox.success(result.msg);
                let data = result.data;
    
                activityOneEndTime.value = data.endTime;//活动结束时间 毫秒值
                clearInterval(activityOneTimer.value);//清空旧定时器
                countDownTime();//初始显示
                activityOneTimer.value = setInterval(countDownTime, 1000);//启动倒计时
                //设置 miaoShaId 
                data.list.forEach( p => {
                    p.miaoShaId = data.id;
                    p.endTime = data.endTime;
                });
                activityOneDataArr.value = data.list;//秒杀商品
            } else {
                DlMessageBox.error(result.msg);
            }
            activityOneDataLoading.value = false;
        });
    }

}
const activityOneTimer = ref();
function countDownTime() {//倒计时处理
    //剩余时间
    let t = activityOneEndTime.value - Date.now();
    if(t <= 0) {//活动结束, 停止倒计时
        clearInterval(activityOneTimer.value);
        activityOneShowTime.value = `活动结束`;
        return;
    }
    //剩余时间 转换为 时分秒
    let h = Math.trunc(t / (60*60*1000));
    let m = Math.trunc( (t % (60*60*1000)) / (60*1000) );
    let s = Math.trunc( (t % (60*1000)) / 1000 );
    if(m < 10) m = '0'+m;
    if(s < 10) s = '0'+s;
    activityOneShowTime.value = `倒计时: ${h}:${m}:${s}`;
}
// 展示更多
function doShowOneMore() {
    menuCore.push('/miaosha');
}

//推荐商品
const recommendProductArr = ref([]);//数据
const currentPageNum = ref(1);
const pageSize = 5;
const pages = ref(0);//总页数
const recommendProductLoading = ref(false);//加载中
const noMoreData = ref(false);//暂无更多数据
function doLoadDataRecommendProduct() {
    if(currentPageNum.value == 1) {
        recommendProductArr.value = [];
    }
    noMoreData.value = false;
    recommendProductLoading.value = true;

    if (window && window.enableDl) {
        //模拟
        setTimeout(()=>{
            let dataArr = [];
    
            let key = recommendProductArr.value.length + 1;
            dataArr.push({id: key, title: '香脆可口红富士', image: './product.jpg', price: 5.99, type:['1斤','2斤','5斤'], status:1});
            for(let i=1;i<5; i++) {
                dataArr.push({id: i+key, title: '测试测试测试测试-'+(i+key), image: './product.jpg', price: 99.99, type:['红色','绿色','蓝色'], status:1});
            }
    
            dataArr.forEach(p => recommendProductArr.value.push(p));
            pages.value = 5;
            noMoreData.value = currentPageNum.value >= pages.value;
            recommendProductLoading.value = false;
        }, 1000);
    } else {
        //请求api
        findRecommendProductFun(currentPageNum.value, pageSize).then((result)=>{
            console.log('findRecommendProductFun result:', result);
            if (result.code == 200) {
                //DlMessageBox.success(result.msg);
                pages.value = result.data.pages;
                result.data.list.forEach(p => recommendProductArr.value.push(p));
                noMoreData.value = currentPageNum.value >= pages.value;
            } else {
                DlMessageBox.error(result.msg);
            }
            recommendProductLoading.value = false;
        });
    }

}

//购物车
const cart = inject('cart');//模拟时使用的
//加入购物车
function doAddCart(product) {
    if(!isLogin.value) {
        DlMessageBox.error('您还未登录,\n请先登录!');
        return;
    }
    // 加入购物车
    if (window && window.enableDl) {
        //模拟
        if(cart[product.id]){
            cart[product.id].num++;
        } else {
            cart[product.id] = {
                productId: product.id, 
                image: product.image, 
                title: product.title, 
                price: product.price, 
                type: product.type, 
                num: 1, checked: false, 
                endTime: product.endTime,
                miaoShaId: product.miaoShaId,
            };
        }
        console.log(cart[product.id]);
        console.log('cart:', cart);
    } else {
        addToCartFun(product.id, product.miaoShaId).then((result)=>{
            if (result.code == 200) {
                //成功后执行以下操作
                DlMessageBox.success(result.msg);
            } else {
                DlMessageBox.error(result.msg);
            }
        });
    }

}

//前往详情页
function goDetail(product) {
    //详情页需要 productId
    localStorage.setItem('detailProductId', product.id);
    menuCore.push('/detail');
}

//主菜单核心
const menuCore = inject('menuCore');
const searchKey = inject('searchKey');
//前往搜索
function goToSearch(key) {
    //console.log('searchKey:', key);
    if(!key || !key.trim()) {
        DlMessageBox.warning({message:'请输入搜索内容', duration: 3000});
        return;
    }
    searchKey.value = key;
    menuCore.push('/search');
}

//登录用户缓存
const loginUser = inject('loginUser');
const isLogin = ref(false);
function doCheckLogin() {
    if(!loginUser.value || !loginUser.value.token) {
        //页面可临时操作
        //menuCore.push('/login');
        return;
    }
    isLogin.value = true;
}

onMounted(()=> {
    doCheckLogin();
    //初始化
    doLoadDataBanner();
    doLoadDataType();
    doLoadActivityOneData();
    doLoadDataRecommendProduct();
});

</script>
<template>
    <div class="view-dl" ref="viewRef" :style="'height:'+viewHeight+'px'" @scroll="doChangeScroll">
        <div class="head-dl">
            <div class="top-title-dl">小桥在线购物</div>
            <!-- 搜索导航区 -->
            <SearchBox @search="goToSearch" :key-word="searchKey" />
        </div>

        <!-- 横幅导航区 -->
        <BannerBox class="banner-div-dl" :arr="bannerArr" :autoplay="false" :speed="5000" />

        <!-- 分类导航区 -->
        <div class="type-list-box-dl">
            <div class="type-list-dl" :style="'width: '+ typeListWidth +'rem'">
                <div class="type-item-dl" v-for="t in typeArr" :key="t.id" @click="goToTypeListView(t)">
                    <div class="type-img-dl">
                        <img :src="t.image" alt="no image">
                    </div>
                    <div class="type-title-dl">{{t.name}}</div>
                </div>
            </div>
        </div>

        <!-- 限时秒杀活动区 -->
        <div class="activity-box-list-dl">
            <div class="activity-top-dl">
                <div class="activity-title-dl">限时秒杀</div>
                <div class="activity-tip-dl">{{activityOneShowTime}}</div>
                <div class="activity-more-dl" @click="doShowOneMore">查看全部</div>
            </div>
            <div class="activity-list-dl">
                <template v-for="p in activityOneDataArr" :key="p.id">
                    <ProductBox :product="p" @go-detail="goDetail" @add-cart="doAddCart" class="pfs-dl" />
                </template>
            </div>
        </div>

        <!-- 推荐商品区 -->
        <div class="activity-box-list-dl">
            <div class="activity-top-dl">
                <div class="activity-title-dl">推荐商品</div>
            </div>
            <div class="recommend-list-dl">
                <template v-for="(p) in recommendProductArr" :key="p.id">
                    <ProductBox :product="p" @go-detail="goDetail" @add-cart="doAddCart" class="pfs-dl" />
                </template>
            </div>

            <div class="load-box-dl" >
                <!-- 加载中动画... -->
                <DlLoading style="font-size: 1rem" v-show="recommendProductLoading" />
                <div class="no-more-data-dl" v-show="!recommendProductLoading && noMoreData">暂无更多推荐商品</div>
            </div>
        </div>
        <!-- 回到顶部 -->
        <div class="top-btn-dl" :style="topBtnStyle">
            <IconTopCircle class="icon-dl" @click="doGoTop" />
        </div>
    </div>
</template>
<style scoped>
.view-dl {
    font-size: 0.4rem;
    overflow: hidden auto;
}
.head-dl {
    background-color: #fff;
    padding: 0.14rem 0.38rem;
    font-size: 1rem;
    color: #333;
}

.top-title-dl {
    font-weight: bold;
    font-size: 0.6rem;
    text-align: center;
}

.banner-div-dl {
    height: 4rem;
    font-size: 0.8rem;
    background-color: #ccc;
    margin: 0.2rem auto;
}

.type-list-box-dl {
    width: 9.2rem;
    height: 5rem;
    background-color: #fff;
    border-radius: 0.08rem;
    margin: 0.2rem auto;
    overflow: auto hidden;
    box-sizing: border-box;
    color: #333;
}
.type-list-dl {
    padding: 0.2rem;
}

.type-item-dl {
    display: inline-block;
    padding: 0.2rem 0.37rem;
    cursor: pointer;
}
.type-img-dl {
    width: 1.4rem;
    height: 1.4rem;
    font-size: 0.28rem;
}
.type-img-dl img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    font-size: 0.24rem;
    display: block;
}
.type-title-dl {
    padding-top: 0.1rem;
    font-size: 0.22rem;
    text-align: center;
}

.activity-box-list-dl {
    width: 9.2rem;
    margin: 0.2rem auto;
    background-color: #fff;
    border-radius: 0.08rem;
    color: #333;
}
.activity-top-dl {
    display: flex;
    margin-bottom: 0.12rem;
    align-items: center;
    padding: 0.1rem;
}
.activity-title-dl {
    font-size: 0.6rem;
    font-weight: bold;
    flex-shrink: 0;
    width: 2.8rem;
}
.activity-tip-dl {
    font-size: 0.3rem;
    font-weight: bold;
    flex: 1 0 auto;
    color:#d00;
}
.activity-more-dl {
    font-size: 0.3rem;
    font-weight: bold;
    color: #999;
    cursor: pointer;
}

.activity-list-dl {
    display: flex;
    height: 3.26rem;
}

.pfs-dl {
    font-size: 1.0875rem;
    padding: 0 0 0.1rem 0.1rem;
}

.recommend-list-dl {
    display: flex;
    flex-wrap: wrap;
}

.load-box-dl {
    text-align: center;
    color: #aaa;
    margin: 0.5rem 0;
    padding: 0.2rem;
}
.load-box-dl .no-more-data-dl {
    border-top: 1px solid #ccc;
    font-size: 0.4rem;
    padding: 0.2rem 0;
}

.top-btn-dl {
    position: fixed;
    transition: all 0.2s linear;
}
.top-btn-dl .icon-dl {
    width: 1.6rem;
    height: 1.6rem;
    color: #fff;
    background-color: #999c;
    border-radius: 50%;
    cursor: pointer;
}
</style>